package hongvt.quanlynhanvien;

import hongvt.quanlynhanvien.database.DatabaseManager;
import hongvt.quanlynhanvien.model.Employee;
import hongvt.quanlynhanvien.model.Timekeeping;
import hongvt.quanlynhanvien.utils.Define;
import hongvt.quanlynhanvien.utils.MyLog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import butterknife.InjectView;

import com.google.gson.Gson;

public class TimekeepingActivity extends AbstractActivity {
	@InjectView(R.id.calendarView)
	CalendarView calendar;

	DatabaseManager dbManagement;
	List<Employee> listEmployees;
	List<Timekeeping> currentListTimekeepings;

	CharSequence[] empItems;

	boolean[] selected;
	boolean[] oldSelected;

	@Override
	protected int getCurrentViewId() {
		// TODO Auto-generated method stub
		return R.layout.activity_timekeeping;
	}

	@Override
	protected void afterInitView() {
		initializeData();
		initializeCalendar();
	}

	public void initializeData() {
		dbManagement = new DatabaseManager(context);
		listEmployees = dbManagement.getListEmployees();

		selected = new boolean[listEmployees.size()];
		oldSelected = new boolean[listEmployees.size()];

		empItems = new CharSequence[listEmployees.size()];

		for (int i = 0; i < listEmployees.size(); i++) {
			empItems[i] = listEmployees.get(i).getName();
		}
	}

	public void initializeCalendar() {
		// sets whether to show the week number.
		calendar.setShowWeekNumber(false);

		// sets the first day of week according to Calendar.
		// here we set Monday as the first day of the Calendar
		calendar.setFirstDayOfWeek(2);

		// The background color for the selected week.
		calendar.setSelectedWeekBackgroundColor(getResources().getColor(
				R.color.green));

		// sets the color for the dates of an unfocused month.
		calendar.setUnfocusedMonthDateColor(getResources().getColor(
				R.color.transparent));

		// sets the color for the separator line between weeks.
		calendar.setWeekSeparatorLineColor(getResources().getColor(
				R.color.transparent));

		// sets the color for the vertical bar shown at the beginning and at the
		// end of the selected date.
		calendar.setSelectedDateVerticalBar(R.color.darkgreen);

		// sets the listener to be notified upon selected date change.
		calendar.setOnDateChangeListener(new OnDateChangeListener() {
			// show the selected date as a toast
			@Override
			public void onSelectedDayChange(CalendarView view, int year,
					int month, int day) {
				showTimekeepingDialog(year, month, day);
			}
		});

		calendar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Calendar cal = Calendar.getInstance();
				cal.clear();
				cal.setTimeInMillis(calendar.getDate());
				int year = cal.get(Calendar.YEAR);
				int month = cal.get(Calendar.MONTH);
				int day = cal.get(Calendar.DAY_OF_MONTH);
//				showTimekeepingDialog(year, month, day);

			}
		});

	}

	public void showTimekeepingDialog(final int year, final int month,
			final int day) {
		currentListTimekeepings = dbManagement.getListTimekeepingByDate(year,
				month, day);

		for (int i = 0; i < selected.length; i++) {
			selected[i] = false;
			oldSelected[i] = false;
		}

		for (int i = 0; i < listEmployees.size(); i++) {
			for (Timekeeping tk : currentListTimekeepings) {
				if (tk.getEmpId().equals(listEmployees.get(i).getEmpId())) {
					selected[i] = true;
					oldSelected[i] = true;
				}
			}
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(day + "/" + (month + 1) + "/" + year);
		builder.setMultiChoiceItems(empItems, selected,
				new OnMultiChoiceClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int which,
							boolean isChecked) {
						selected[which] = isChecked;

					}
				});

		builder.setPositiveButton(getText(R.string.done),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						updateData(year, month, day);
					}
				});

		builder.setNegativeButton(getText(R.string.cancel), null);

		builder.create().show();
	}

	public void updateData(int year, int month, int dayOfMonth) {
		MyLog.i("selected", new Gson().toJson(selected));
		MyLog.i("oldselected", new Gson().toJson(oldSelected));

		List<Timekeeping> delListTimekeepings = new ArrayList<Timekeeping>();
		List<Timekeeping> insertListTimekeepings = new ArrayList<Timekeeping>();

		for (int i = 0; i < selected.length; i++) {
			if (selected[i] != oldSelected[i]) {
				if (oldSelected[i]) {
					for (Timekeeping tk : currentListTimekeepings) {
						if (tk.getEmpId().equals(
								listEmployees.get(i).getEmpId())) {
							delListTimekeepings.add(tk);
							break;
						}
					}
				} else {
					SimpleDateFormat sdf = new SimpleDateFormat(
							Define.TIME_FORMAT_YYYY_MM_DD);
					Calendar cal = Calendar.getInstance();
					cal.clear();
					cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
					cal.set(Calendar.MONTH, month);
					cal.set(Calendar.YEAR, year);

					String date = sdf.format(cal.getTime());

					Timekeeping tk = new Timekeeping();
					tk.setEmpId(listEmployees.get(i).getEmpId());
					tk.setDate(date);

					MyLog.i("tk", new Gson().toJson(tk));

					insertListTimekeepings.add(tk);

				}
			}
		}

		MyLog.i("del", new Gson().toJson(delListTimekeepings));
		MyLog.i("insert", new Gson().toJson(insertListTimekeepings));
		dbManagement.deleteListTimekeeping(delListTimekeepings);
		dbManagement.insertListTimekeeping(insertListTimekeepings);
	}
}
